#! /usr/bin/python2.5
#
# TODO: This program use for start/stop/restart server
#		or initial the database or run tests
#
import os
import signal
import sys

from common import config
from server import Server
from database.database_controllor import DatabaseControllor
from utils.initdb_util import DBOperator
from common import datasetInfo

def startServer():
    if os.access(config.PID_FILE, os.R_OK):
        print "ERROR: DMAWeb server has already started"
        sys.exit()
    pid = os.fork()
    if not pid:
        """Child thread"""
        pid = os.getpid()
        pid_file = file(config.PID_FILE, 'w')
        pid_file.write(str(pid) + "\n")
        pid_file.close()
        server = Server()
        print "Server start ... ..."
        server.start_server()

def stopServer():
    if os.access(config.PID_FILE, os.R_OK):
        pid_file = file(config.PID_FILE, 'r')
        pid = int(pid_file.readline().strip())
        pid_file.close()
        os.kill(pid, signal.SIGTERM)
        os.unlink(config.PID_FILE)
        print "Server stop ... ..."
    else:
        print "ERROR: DMAWeb server has not started"

def initialDatabase():
    db = DBOperator()
    try:
        db.createDB()
    except StandardError, err:
        print "ERROR:", err

def importDataset():
    sqlfile = getattr(config, 'SQL_FILE')
    dataset= getattr(config, 'DATASET')
    table = getattr(config, 'TABLE_NAME')
    attributes = getattr(config, 'ATTRIBUTE_LIST')
    types = getattr(config, 'TYPE_LIST')
    db = DBOperator()
    try:
        db.applyDBFiles(sqlfile)
        con = DatabaseControllor()
        con.connect()
        con.importDataset(dataset, table, attributes)
        con.disconnect()
        
        #edit the file datasetInfo, to add information of new dataset
        table_list = getattr(datasetInfo, 'table_list')
        table_list.append(table)
        attribute_list = getattr(datasetInfo, 'attribute_list')
        attribute_list[table] = attributes
        attributeInfo_list = getattr(datasetInfo, 'attributes')
        new_attribute_info = []
        attributes_name = attributes.split(', ')
        attributes_type = types.split(', ')
        i = 0
        for name in attributes_name:
            new_attribute_info.append({"name": name, "type": attributes_type[i]})
            i = i + 1
        attributeInfo_list["attributeList"].append({"table": table, "attributes": new_attribute_info})
        
        os.remove("common/datasetInfo.py")
        f = open("common/datasetInfo.py", 'w')
        f.write("table_list = ")
        f.write(str(table_list))
        f.write("\nattribute_list = ")
        f.write(str(attribute_list))
        f.write("\nattributes = ")
        f.write(str(attributeInfo_list))
        f.close()

    except StandardError, err:
        print "ERROR:", err

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print """
===========================================================
Usage: dmaweb OPTION

    OPTION:
        restart:    Restart the DMAWeb server
        start:      Start the DMAWeb server
        stop:       Stop the DMAWeb server
===========================================================
        """
        sys.exit()

    if sys.argv[1] == "start":
        startServer()
    elif sys.argv[1] == "stop":
        stopServer()
    elif sys.argv[1] == "restart":
        stopServer()
        startServer()
    elif sys.argv[1] == "initdb":
        initialDatabase()
    elif sys.argv[1] == "adddata":
        importDataset()
        

